package hello.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import hello.base.HttpResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "文件相关")
@Controller
@RequestMapping("/files")
@Slf4j
public class FileController {

    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
    public final static String UPLOAD_PATH_PREFIX = "src/main/resources/static/uploadFile/";

    public final static String GET_PATH_PREFIX = "uploadFile/";


    @ApiOperation(value = "上传文件")
    @PostMapping(value = "")
    @ResponseBody
    public HttpResponse post(@RequestBody MultipartFile file, HttpServletRequest request) {

        HttpResponse rsp = new HttpResponse();
        String key = null;
        try {
            key = uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            rsp.setCode(400);
            rsp.setMsg("上传失败");
            return rsp;
        }


        String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + key;
        JSONObject json = new JSONObject();
        json.put("key", key);
        json.put("url", "localhost:8080/" + GET_PATH_PREFIX + key);
        json.put("size", file.getSize());
        json.put("name", file.getOriginalFilename());
        rsp.setData(json);
        rsp.setMsg("上传成功");

        return rsp;
    }


    private String uploadFile(MultipartFile uploadFile) throws IOException {

        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());

        String realPath = new String(UPLOAD_PATH_PREFIX);

        File tempFile = new File(realPath);
        if (!tempFile.isDirectory()) {
            //递归生成文件夹
            tempFile.mkdirs();
        }

        //构建真实的文件路径
        File newFile = new File(tempFile.getAbsolutePath() + File.separator + newName);
        //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
        uploadFile.transferTo(newFile);

        return newName;
    }
}
